﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using DAL.Entity;
using DAL.Persistencia;
using BLL.Utils;

namespace NewTierra.Pages.MontarServicos
{
    public partial class MontarServicoConsulta : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                popularDrops();
                //popularGridMServico(sender, e);
            }
        }

        #region Popular Dados

        protected void popularDrops()
        {
            popularDropTipoTransporte();
            popularDropTipoServico();
            popularDropTipoServicoCateg();
            popularDropMoeda();
        }

        protected void popularDropTipoTransporte()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoTransporte.DataSource = Con.Tipo_Transporte.OrderBy(t => t.TipoTrans_nome).ToList();
                    ddlTipoTransporte.DataTextField = "TipoTrans_nome";
                    ddlTipoTransporte.DataValueField = "IdTipoTrans";
                    ddlTipoTransporte.DataBind();
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void popularDropTipoServico()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlTipoServico.DataSource = Con.S_Servicos_Tipo.ToList();
                    ddlTipoServico.DataTextField = "Tipo_Nome";
                    ddlTipoServico.DataValueField = "Tipo_Id";
                    ddlTipoServico.DataBind();
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void ddlTipoServico_SelectedIndexChanged(object sender, EventArgs e)
        {
            popularDropTipoServicoCateg();
        }

        protected void popularDropTipoServicoCateg()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    int IdServico = Convert.ToInt32(ddlTipoServico.SelectedValue);
                    ddlTipoServicoCateg.DataSource = Con.S_Servicos_Tipo_Categ.Where(t => t.Tipo_Id == IdServico).OrderBy(t => t.Tipo_categ_nome).ToList();
                    ddlTipoServicoCateg.DataTextField = "Tipo_categ_nome";
                    ddlTipoServicoCateg.DataValueField = "Tipo_categ_id";
                    ddlTipoServicoCateg.DataBind();
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void popularDropMoeda()
        {
            try
            {
                using (NewTierraEntities Con = new NewTierraEntities())
                {
                    ddlMoeda.DataSource = Con.Moeda.OrderBy(t => t.Moeda_sigla).ToList();
                    ddlMoeda.DataTextField = "Moeda_sigla";
                    ddlMoeda.DataValueField = "Moeda_id";
                    ddlMoeda.DataBind();
                }
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void popularGridMServico(object sender, EventArgs e)
        {
            try
            {
                MontaServicoDAL m = new MontaServicoDAL();

                GridMServico.DataSource = m.ListarTodos();
                GridMServico.DataBind();

                MergeRows(GridMServico);
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }               

        public static void MergeRows(GridView gridView)
        {
            for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--)
            {
                GridViewRow row = gridView.Rows[rowIndex];
                GridViewRow previousRow = gridView.Rows[rowIndex + 1];

                for (int i = 0; i < row.Cells.Count; i++)
                {
                    if (row.Cells[i].Text == previousRow.Cells[i].Text)
                    {
                        row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 :
                                               previousRow.Cells[i].RowSpan + 1;
                        previousRow.Cells[i].Visible = false;
                    }
                }
            }
        }

        #endregion

        #region CRUD Montar Servico

        protected void SalvarMontarServico(object sender, EventArgs e)
        {
            try
            {
                if (txtCodServico.Text != "")
                {
                    LimpaCampos(this.Controls);
                    lblMsgCadMServicos.Text = "";
                    btnNovoMServico.Text = "Salvar";
                    Session.Abandon();
                    txtSupplier.Focus();
                    return;
                }

                Monta_Servico m = new Monta_Servico();
                SupplierDAL s = new SupplierDAL();

                m.MServico_De = txtDe.Text;
                m.MServico_Para = txtPara.Text;
                m.MServico_CapMaxima = txtCapTotal.Text;
                m.MServico_Bulk = Convert.ToDecimal(txtBulk.Text);
                m.MServico_Bulk_Total = Convert.ToDecimal(txtBulkTotal.Text);
                m.MServico_Bulk_Porc_Taxa = Convert.ToInt32(txtPorcentagemTaxa.Text);
                m.MServico_Bulk_Porc_Imposto = Convert.ToInt32(txtPorcentagemImposto.Text);
                m.MServico_Bulk_Porc_Comissao = Convert.ToInt32(txtComissao.Text);
                m.MServico_DataFrom = Convert.ToDateTime(from.Text);
                m.MServico_DataTo = Convert.ToDateTime(to.Text);
                m.MServico_Obs = txtObs.Text;
                m.IdTipoTrans = Convert.ToInt32(ddlTipoTransporte.SelectedValue);
                m.S_id = s.FindAllNome(txtSupplier.Text).S_id;
                m.Tipo_Id = Convert.ToInt32(ddlTipoServico.SelectedValue);
                m.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg.SelectedValue);
                m.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                MontaServicoDAL d = new MontaServicoDAL();
                d.Salvar(m);
                LimpaCampos(this.Controls);
                txtPorcentagemTaxa.Text = "0";
                txtPorcentagemImposto.Text = "0";
                txtComissao.Text = "0";
                lblMsgCadMServicos.Text = "Registro cadastrado com sucesso.";
                popularGridMServico(sender, e);
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }

        }

        protected void AtualizarMontarServico(object sender, EventArgs e)
        {
            try
            {
                if (txtCodServico.Text == "")
                {
                    lblMsgCadMServicos.Text = "Selecione um serviço para ser atualizado.";
                    return;
                }

                Monta_Servico m = new Monta_Servico();
                SupplierDAL s = new SupplierDAL();

                m.IdMServico = Convert.ToInt32(txtCodServico.Text);
                m.MServico_De = txtDe.Text;
                m.MServico_Para = txtPara.Text;
                m.MServico_CapMaxima = txtCapTotal.Text;
                m.MServico_Bulk = Convert.ToDecimal(txtBulk.Text);
                m.MServico_Bulk_Total = Convert.ToDecimal(txtBulkTotal.Text);
                m.MServico_Bulk_Porc_Taxa = Convert.ToInt32(txtPorcentagemTaxa.Text);
                m.MServico_Bulk_Porc_Imposto = Convert.ToInt32(txtPorcentagemImposto.Text);
                m.MServico_Bulk_Porc_Comissao = Convert.ToInt32(txtComissao.Text);
                m.MServico_DataFrom = Convert.ToDateTime(from.Text);
                m.MServico_DataTo = Convert.ToDateTime(to.Text);
                m.MServico_Obs = txtObs.Text;
                m.IdTipoTrans = Convert.ToInt32(ddlTipoTransporte.SelectedValue);
                m.S_id = s.FindAllNome(txtSupplier.Text).S_id;
                m.Tipo_Id = Convert.ToInt32(ddlTipoServico.SelectedValue);
                m.Tipo_categ_id = Convert.ToInt32(ddlTipoServicoCateg.SelectedValue);
                m.Moeda_id = Convert.ToInt32(ddlMoeda.SelectedValue);

                MontaServicoDAL d = new MontaServicoDAL();
                d.Atualizar(m);
                LimpaCampos(this.Controls);
                popularGridMServico(sender, e);
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        protected void DeleteMontarServico(object sender, EventArgs e)
        {
            try
            {
                if (txtCodServico.Text == "")
                {
                    lblMsgCadMServicos.Text = "Selecione um serviço para ser excluído.";
                    return;
                }

                MontaServicoDAL m = new MontaServicoDAL();

                Monta_Servico ms = m.ObterPorId(Convert.ToInt32(txtCodServico.Text));

                m.Excluir(ms);
                Session.Abandon();
                LimpaCampos(this.Controls);
                btnNovoMServico.Text = "Salvar";
                lblMsgCadMServicos.Text = "Serviço excluído com sucesso.";
                popularGridMServico(sender, e);
            }
            catch (Exception ex)
            {
                lblMsgCadMServicos.Text = ex.Message;
            }
        }

        #endregion

        #region Regras

        [WebMethod]
        public static List<string> SearchSuppliers(string prefixText, int count)
        {
            try
            {
                SupplierDAL s = new SupplierDAL();

                List<Supplier> supp = s.ListarTodos(prefixText);

                List<string> lista = new List<string>();

                foreach (Supplier p in supp)
                {
                    lista.Add(p.S_nome);
                }

                return lista;
            }
            catch
            {
                throw;
            }
        }

        protected void txtBulk_TextChanged(object sender, EventArgs e)
        {

            Utils u = new Utils();

            if (u.ValidaNumeroComVirgula(txtBulk.Text))
            {
                txtPorcentagemTaxa_TextChanged(sender, e);
                lblErroBulk.Text = "";
            }
            else
            {
                lblErroBulk.Text = "Digitar somente números.";
                lblErroBulk.ForeColor = System.Drawing.Color.Red;
                return;
            }


        }

        protected void txtPorcentagemTaxa_TextChanged(object sender, EventArgs e)
        {
            if (!txtBulk.Text.Equals(""))
            {
                if (!txtPorcentagemTaxa.Equals(""))
                {
                    double valortarifa = Convert.ToDouble(txtBulk.Text);
                    double valortotalComTaxa = (valortarifa * Convert.ToDouble(txtPorcentagemTaxa.Text)) / 100;

                    double d = Convert.ToDouble(valortarifa + valortotalComTaxa);
                    txtBulkTotal.Text = d.ToString("N2");

                    double valortarifa2 = Convert.ToDouble(txtBulkTotal.Text);
                    double valortotalComImposto = (valortarifa2 * Convert.ToDouble(txtPorcentagemImposto.Text)) / 100;

                    double d2 = Convert.ToDouble(valortarifa2 + valortotalComImposto);
                    txtBulkTotal.Text = d2.ToString("N2");
                }
                else
                {
                    txtBulk.Text = "";
                }
            }
            else
            {
                lblMsgCadMServicos.Text = "Favor digitar o valor do bulk antes das taxas.";
            }
        }

        protected void txtComissao_TextChanged(object sender, EventArgs e)
        {
            if (txtBulk.Text != "")
            {
                txtPorcentagemTaxa_TextChanged(sender, e);

                double valortarifa = Convert.ToDouble(txtBulk.Text);
                double valortotalComComissao = (valortarifa * Convert.ToDouble(txtComissao.Text)) / 100;

                double d = Convert.ToDouble(Convert.ToDouble(txtBulkTotal.Text) - valortotalComComissao);
                txtBulkTotal.Text = d.ToString("N2");
            }
            else
            {
                lblMsgCadMServicos.Text = "Favor digitar o valor do bulk antes das taxas.";
            }
        }

        protected void Limpar(object sender, EventArgs e)
        {
            LimpaCampos(this.Controls);
        }

        protected void LimpaCampos(ControlCollection controls)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl is TextBox)
                {
                    (ctrl as TextBox).Text = string.Empty;
                }
                // ... demais controles que queira limpar

                LimpaCampos(ctrl.Controls);
            }
        }

        protected void LimpaLabel(object sender, EventArgs e)
        {
            lblMsgCadMServicos.Text = "";
        }

        protected void MontaGridPorSupplier(object sender, EventArgs e)
        {
            popularGridMServico(sender, e);
        }

        #endregion


    }
}